package com.project.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.project.common.Result;
import com.project.common.UserHolder;
import com.project.entity.User;
import com.project.entity.redis.UserInfo;
import com.project.service.UserService;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.project.common.RedisConstants.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Ao
 * @since 2024-04-24
 */

@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {
    @Autowired
    private UserService userService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //生成一个查询所有用户接口
    @GetMapping("/findAll")
    @ApiOperation("查询所有用户")
    public Result<List<User>> findAll() {

        List<User> list = userService.list();

        return Result.success(list);
    }

    //使用redis实现session共享的登录接口

    /**
     * 登录接口
     */
    @ApiOperation(value = "登录接口", notes = "登录接口")
    @PostMapping("/login")
    @Transactional
    public Result<?> login(@Validated @RequestBody User user) {
        return userService.login(user);
    }


    @GetMapping("/loginOut")
    @ApiOperation(value = "退出登录", notes = "退出登录")
    public Result<String> loginOut(HttpServletRequest request){
        //1,获取请求头中的token
        String token = request.getHeader("token");
        String key=LOGIN_USER_KEY+token;

        //2,删除学生--String类型
        stringRedisTemplate.delete(key);

        UserInfo user2 = UserHolder.getUser();
        String userJson = JSONUtil.toJsonStr(user2);

        //删除学生--zset类型里元素
        stringRedisTemplate.opsForZSet().remove(ONLINE_STUDENTLIST_KEY,userJson);

        return Result.success("登录退出");
    }


    @RequestMapping(value = "test", method = RequestMethod.GET)
    public String test() {
        return "test";
    }


    //用户生成token，存入redis，设置过期时间，key是uuid值，value是user对象
//    @GetMapping("/login2")
}

